package com.heima.reggie.controller;

import com.heima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String path;
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile img){
        log.info("{}", img);
        //获取文件全名
        String name = img.getOriginalFilename();
        //获取文件后缀
        String houzhui = name.substring(name.lastIndexOf("."));
        String uuid = UUID.randomUUID()+houzhui;
        File file1 = new File(path);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        try {
            img.transferTo(new File(path,uuid));
        } catch (IOException e) {
            e.printStackTrace();
        }


        return R.success(uuid);

    }
@GetMapping("/download")
public void download(String name, HttpServletRequest request , HttpServletResponse response){

    try {
    FileInputStream fit = new FileInputStream(new File(path+name));
    ServletOutputStream outputStream = response.getOutputStream();
    response.setContentType(request.getServletContext().getMimeType(name));

        IOUtils.copy(fit,outputStream);
        outputStream.flush();
        fit.close();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}


}
